﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Vk.Common;
using VkontakteInfrastructure.Model;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace VkVideoPlayer.UI
{
	public partial class MainPage : PhoneApplicationPage
	{
		private ScrollViewer scroller;
		private object selectedItem;
		// Constructor
		public MainPage()
		{
			InitializeComponent();

			// Set the data context of the listbox control to the sample data
			DataContext = App.ViewModel;
			this.Loaded += new RoutedEventHandler(MainPage_Loaded);
		}

		// Load data for the ViewModel Items
		private void MainPage_Loaded(object sender, RoutedEventArgs e)
		{
			scroller = Tools.FindChildRecursive<ScrollViewer>(FirstListBox, App.ViewModel);
		}

		protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
		{
			base.OnNavigatedFrom(e);
			App.ViewModel.OnNavigatedFrom(this, e);
		}

		protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
		{
			base.OnNavigatedTo(e);
			App.ViewModel.OnNavigatedTo(this, e);
		}

		private void FirstListBox_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
		{
			
		}

		private void FirstListBox_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
		{

		}

		private void FirstListBox_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
		{

		}

		private void FirstListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			selectedItem = e.AddedItems;
			
		}

		private void FirstListBox_Tap(object sender, GestureEventArgs e)
		{
			
			if (selectedItem != null)
			{
		//		var item = (Video) selectedItem;
				var center = FirstListBox.ActualHeight/2 - 100; // 100 is a height of stack panel
				var pos = e.GetPosition(FirstListBox);
				var y = pos.Y;
				//MessageBox.Show(pos.X + "   " + pos.Y);
				if(center < y) // tap in bottom part of list
				{
					y = -y;
				}
				scroller.ScrollToVerticalOffset(center);
				selectedItem = null;
				e.Handled = true;
			}
		}
	}
}